package com.analysis.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.analysis.model.KLine;

public class StoreService  {

	private static Map<String, List<KLine>> datas = new ConcurrentHashMap<>();
	private static Map<String, int[]> zigzags = new ConcurrentHashMap<>();
	private static Map<String, double[]> normalizes = new ConcurrentHashMap<>();
	private static StoreService storeService = new StoreService();
	
	private StoreService(){ 
	}
	public static StoreService getInstance(){
		return storeService;
	}

	public List<KLine> getKline(String symbol) {
		List<KLine> list = datas.get(symbol);
		return CollectionUtils.isEmpty(list) ? new ArrayList<>() : new ArrayList<>(list);
	}

	public void saveKline(String symbol, List<KLine> klines) {
		if (StringUtils.isNotEmpty(symbol) && CollectionUtils.isNotEmpty(klines)) {
			datas.put(symbol, klines);
		}
	}

	public int[] getZigzag(String symbol) {
		return zigzags.get(symbol);
	}

	public void saveZigzag(String symbol, int[] zigzag) {
		if (StringUtils.isNotEmpty(symbol) && zigzag != null && zigzag.length != 0) {
			zigzags.put(symbol, zigzag);
		}
	}
	
	public double[] getNormalize(String symbol) {
		return normalizes.get(symbol);
	}

	public void saveNormalize(String symbol, double[] zigzag) {
		if (StringUtils.isNotEmpty(symbol) && zigzag != null && zigzag.length != 0) {
			normalizes.put(symbol, zigzag);
		}
	}

	public void writeToFile(File file, List<Double> data) {
		try {
			FileUtils.writeLines(file, data, false);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void deleteFile(File file) {
		FileUtils.deleteQuietly(file);
	}

	public List<String> readFile(File file) {
		try {
			if (file.exists()) {
				return FileUtils.readLines(file, Charset.defaultCharset());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	public void writeKlineClose(String symbol, List<Double> data) {
		File input = Paths.get("./kline/data/" + symbol + ".txt").toFile();
		writeToFile(input, data);
	}
}
